<script>
import {
  computed,
  defineComponent,
  inject,
  onUnmounted,
  reactive,
  ref,
  toRaw,
  watch,
} from 'vue'
import { libFileList, libRename, tagList } from '@Config/server/api'
import DataTable from '@Components/dataTable'
import { createPagination, Messages, uploadParams } from '@Config/config'
import { message, Modal } from 'ant-design-vue'
import MakeForm, { MakeFormState } from '@Components/makeForm'
import ColorBlock from '@Components/colorBlock'
import { useUrl, transform_pre_fn } from '@Hooks/url'
import { useRoute } from 'vue-router'
import FolderList from '@Components/folderList'
import { cloneDeep, findIndex, flattenDeep, uniqueId } from 'lodash'
import { useStore } from 'vuex'
import useBreadcrumb from '@Hooks/breadcrumb'
import { confirm } from '@Config/config'
import { useWin } from '@Hooks/win'
import ReName from '@Page/my/components/rename'
import RelationPath from '@Page/my/components/relationPath'
import * as Antd from 'ant-design-vue'
import { instanceFn } from '@Page/my/fn'
import FavoritePath from '@Page/favorites/components/favoritePath'
import FileAttribute from '@Page/my/components/fileAttribute'
import { maxSearchValue } from '@Untils'
import { fileType } from '@Config/const'
import { fileApi } from '@Hooks/fileApi'
import Tips from '@Components/tips'

export default defineComponent({
  components: {
    DataTable,
    MakeForm,
    ColorBlock,
    FolderList,
    ReName,
    FavoritePath,
    RelationPath,
    FileAttribute,
  },
  setup(props, context) {
    let store = useStore()
    let route = useRoute()
    const isPublic = ref(1) //发布状态  1:已发布 0:未发布
    let {
      operMenu,
      selectAllHandler,
      tagList_filter,
      getTagList,
    } = instanceFn()
    /**
     * 单个操作和多个操作的api集合
     */
    let {
      removeFile,
      moveToTrash,
      reName,
      rePos,
      downLoad,
      favorite,
      unPublish,
      batchMove,
      batchReoveFile,
      batchToTrash,
      reposByDrag,
      singleFileTags,
      fileThemes,
      batchFileTags,
      createFolder,
      createFile,
      beforeUploadFile,
      shareToFriends,
    } = fileApi()
    //tagList
    getTagList()
    let form_config = [
      {
        key: 'fileType',
        initValue: null,
        source: fileType(),
        uiType: 'dselect',
        col: { span: 4 },
        formItem: { label: '类型' },
        attr: {
          placeholder: '文件类型',
        },
      },
      {
        key: 'dataStatus',
        initValue: 0,

        ignore: true,
      },
      {
        key: 'id',
        initValue: 0,
        ignore: true,
      },
      {
        key: 'isPublic',
        initValue: isPublic.value,
        ignore: true,
      },
      {
        key: 'name',
        initValue: null,
        uiType: 'input',
        col: { span: 4 },
        formItem: { label: '名称' },
        attr: {
          placeholder: '文件名称',
          allowClear: true,
          ...maxSearchValue(20),
        },
      },
      tagList_filter,

      {
        key: 'btns',
        initValue: null,
        uiType: 'custom',
        col: { span: 4 },
        ui: (
          <a-space>
            <a-button
              type="primary"
              onClick={() => {
                pagination.data.current = 1
                searchData()
              }}
            >
              搜索
            </a-button>
            <a-button
              type="primary"
              danger
              onClick={() => {
                form_ref.value.resetState(cloneDeep(_bak_statue))
                pagination.data.current = 1
                searchData()
              }}
            >
              重置
            </a-button>
          </a-space>
        ),
      },
    ]

    let form_state = reactive({ data: MakeFormState(form_config) })
    let _bak_statue = { ...toRaw(form_state.data) }

    //表格数据配置
    let tableData = reactive({
      data: {
        source: [],
        columns: [],
      },
    })

    //表格loading状态
    let loading = reactive({ search_loading: false })

    let { fromStateToQuery, forceFresh } = useUrl({
      fn: async () => {
        loading.search_loading = true
        let _params = {
          ...form_state.data,
          index: pagination.data.current,
          size: pagination.data.pageSize,
        }
        let _result = await libFileList(_params)
        loading.search_loading = false

        if (_result.code != 0) {
          Messages.add(message.error('查询失败' + _result.msg))
          pagination.data.pageSize = 0
          pagination.data.current = 1
          pagination.data.total = 0
          tableData.data.source = []
        } else {
          pagination.data.pageSize = _result.data?.size
          pagination.data.current = _result.data?.index
          pagination.data.total = _result.data?.total
          tableData.data.source = _result.data?.records
        }
      },
      formState: [
        {
          key: 'id',
          fn: transform_pre_fn['fn.number0'],
          default: 0,
        },
        {
          key: 'fileType',
          fn: transform_pre_fn['fn.number0'],
        },
        {
          key: 'dataStatus',
          fn: transform_pre_fn['fn.number0'],
          default: 0,
        },
        {
          key: 'isPublic',
          fn: transform_pre_fn['fn.number0'],
          default: isPublic.value,
        },
        {
          key: 'tagIdList',
          fn: transform_pre_fn['fn.array'],
        },
        {
          key: 'name',
          fn: transform_pre_fn['fn.string'],
        },
      ],
    })
    //查询数据
    let searchData = async () => {
      fromStateToQuery({ path: route.path })
    }
    //表格分页
    let pagination = reactive({
      data: createPagination(searchData, true, false),
    })

    //ref dom
    let form_ref = ref(null)
    //新增公告回调函数

    //默认查询
    //searchData()
    let [addPath] = useBreadcrumb({ key: 'id' })

    //双击文件夹
    let selectHandler = (e) => {
      //searchHandler()
      form_state.data.id = e.target.id
      tableData.data.source.map((x) => {
        if (x.id == e.target.id) {
          x.local_loading = true
        }
      })
      fromStateToQuery({ path: route.path })
      addPath({ ...e.target })
    }

    //注册右上角的菜单
    let rightMenu = inject('rightIconMenu')
    //右上角菜单
    rightMenu.data = [
      {
        ui: (
          <a-menu-item>
            <a-upload
              {...uploadParams()}
              data={{ id: route.query.id || 0, isPublic: isPublic.value }}
              onChange={createFile}
              beforeUpload={beforeUploadFile}
            >
              <a-button type="link" size="small">
                上传文件
              </a-button>
            </a-upload>
          </a-menu-item>
        ),
      },
      {
        ui: (
          <a-menu-item onClick={createFolder}>
            <a-button type="link" size="small">
              创建文件夹
            </a-button>
          </a-menu-item>
        ),
      },
    ]

    //监听 文件夹、文件是否选中
    let checkBoxHandler = (e) => {
      let _index = findIndex(tableData.data.source, { id: e.target.id })
      tableData.data.source[_index].selected = e.e.target.checked
    }

    /**
     * 选中的单位
     */
    let tables_selected = computed(() => {
      return tableData.data.source.filter((x) => x.selected)
    })
    //右键菜单
    let rightMenuHandler = (e) => {
      if (!e.rightMenu) {
        e.rightMenu = (
          <Antd.Menu selectedKeys={[]} class="mymenu">
            {rightMenu.data?.map((x) => x.ui)}
            {operMenu().map((x) => {
              return (
                <Antd.MenuItem>
                  <Antd.Button
                    type="link"
                    onClick={x.action}
                    size="small"
                    disabled={tables_selected.value.length == 0}
                    {...x.attr}
                  >
                    {x.label}
                  </Antd.Button>
                </Antd.MenuItem>
              )
            })}
            <Antd.MenuItem>
              <Antd.Button type="link" onClick={forceFresh} size="small">
                刷新
              </Antd.Button>
            </Antd.MenuItem>
          </Antd.Menu>
        )
      }
    }

    //右键文件，弹出菜单选项
    let folder_right_menu_fn = () => {
      return (_folder) => {
        let _r = [
              {
            label: '下载',
            action: (x) => {
              return downLoad.bind(null, [x])()
            },
          },
          // {
          //   label: '删除',
          //   action: removeFile,
          // },
      
          {
            label: '重命名',
            action: reName,
          },
          {
            label: '移动',
            action: (x) => rePos(x, isPublic.value),
          },
      
          {
            label: '备份',
            action: (x) => {
              return favorite.bind(null, [x.id])()
            },
          },
          {
            label: '加密',
            action: (x) => {
              unPublish([x])
            },
          },
          {
            label: '删除',
            action: moveToTrash,
          },
          {
            label: '分享给好友',
            action: shareToFriends,
          },
        ]
        if (_folder.fileType == 0) {
          let _index = findIndex(_r, { label: '打标签' })
          if (_index >= 0) {
            _r.splice(_index, 1)
          }
          _index = findIndex(_r, { label: '详情' })
          if (_index >= 0) {
            _r.splice(_index, 1)
          }
        }
        return _r
      }
    }

    let _w = watch(
      () => form_state.data.tagIdList,
      () => {
        searchData()
      }
    )
    onUnmounted(() => {
      _w()
    })
    return {
      tableData,
      loading,
      pagination,
      form_config,
      form_state,
      form_ref,
      selectHandler,
      checkBoxHandler,
      selectAllHandler,
      tables_selected,
      rightMenuHandler,
      operMenu,
      forceFresh,
      folder_right_menu_fn,
      isPublic,
      searchData,
      removeFile,
      moveToTrash,
      reName,
      rePos,
      downLoad,
      favorite,
      unPublish,
      batchMove,
      batchReoveFile,
      batchToTrash,
      reposByDrag,
      batchFileTags,
      createFolder,
    }
  },
  render() {
    return (
      <a-row gutter={[20, 20]}>
        <a-col span={24}>
          <MakeForm
            ref="form_ref"
            class="search_form"
            formConfig={this.form_config}
            value={this.form_state.data}
            enterCallBack={() => {
              this.pagination.data.current = 1
              this.searchData()
            }}
          />
        </a-col>
        <a-col span={24}>
          {this.loading.search_loading ? (
            <a-spin tip="数据加载中..." />
          ) : (
            <a-row gutter={[20, 20]} onContextmenu={this.rightMenuHandler}>
              <a-col span={24}>
                <Tips
                  list={this.tableData.data.source}
                  selected={this.tables_selected}
                >
                  <a-space>
                    {this.operMenu().map((x) => {
                      return (
                        <a-button
                          type="primary"
                          onClick={x.action}
                          shape="circle"
                          disabled={this.tables_selected.length == 0}
                          {...x.attr}
                          title={x.label}
                        >
                          {x.icon}
                        </a-button>
                      )
                    })}
                    <a-checkbox onChange={this.selectAllHandler}>
                      全选
                    </a-checkbox>
                  </a-space>
                </Tips>
              </a-col>
              <a-col span={24} class="vh69">
                <FolderList
                  list={cloneDeep([...this.tableData.data.source])}
                  onSelect={this.selectHandler}
                  onCheckBox={this.checkBoxHandler}
                  onReposDrop={this.reposByDrag}
                  rightMenuFn={this.folder_right_menu_fn()}
                  role="common"
                />
                <a-affix {...this.pagination_affix_attr()}>
                  <div class="affix">
                    <a-pagination {...this.pagination.data} />
                  </div>
                </a-affix>
              </a-col>
            </a-row>
          )}
        </a-col>
      </a-row>
    )
  },
})
</script>
